#coding=utf-8
#!/usr/bin/python

'''
Created on 2012-11-17

@author: Neo.Chen
'''

import threading
import time
import dataconvert
import execcmd

#-------------------------------------------------------------------------------
#检测是否到达每天启动一次的时间
def checkRestartForTime(self):
    result = False
    #每天定时重启一次
    str = time.ctime(time.time())
    start = 0
    npos = str.find("00:15:", start)
    if npos != -1:
        result = True
    return result


#-------------------------------------------------------------------------------
#进程CPU监控类，发现某个进程cpu高，就通知应用层
class CProcCpuMonitor():
    #构造函数
    #procName表示被监控的进程名称，maxCpu是最大cpu上限，minCpu是最低下限，maxErrorCount是最大错误次数
    def __init__(self, procName, maxCpu, minCpu, maxErrorCount):
        print("CProcCpuMonitor procname:", procName)
        self.m_procName = procName
        self.m_maxCpu = maxCpu
        self.m_minCpu = minCpu
        self.m_maxErrorCount = maxErrorCount
        self.m_nErrorCount = 0

    #析构函数
    def __del__(self):
        pass

    #检测被监控进程是否有错误（没启动、或者cpu高），返回(isError, fCpu)
    def checkIsError(self):
        result = False
        print("\r\n checkIsError: get sub subproc start")

        #得到cpu数值
        isError = False
        fCpu = 0.0
        (result, fCpu) = self.getSubProcCpu()
        #判断返回值
        if result == False:
            isError = True
        else:
            if (fCpu > self.m_maxCpu) or (fCpu < self.m_minCpu):
                isError = True
                print("overflow min cpu:", self.m_minCpu, ", max cpu:", fCpu > self.m_maxCpu)
            else:
                isError = False

        #对错误进行统计
        self.m_nErrorCount = self.m_nErrorCount + 1
        if self.m_nErrorCount < self.m_maxErrorCount:
            isError = False
        #返回结果
        return (isError, fCpu)


    #获取子进程cpu，返回值（是否提取到，cpu数值）
    def getSubProcCpu(self):
        fCpu = 0.0
        result = False
        print("\r\n getSubProcCpu: get sub subproc start")

        #获取子进程pid
        pid = self.getSubProcessPID()
        if pid == 0:
            return (result, fCpu)
        print("getSubProcCpu: get sub subproc end, pid:", pid)

        #得到pid对应的cpu使用率
        '''
        # ps aux|grep vcs_reclive | grep -v sh | grep 25961
        root     25961  4.4  0.8 521696 71504 ?        Rl   Sep12  83:46 ./vcs_reclive
        '''
        lineList = []
        try:
            lineList = execcmd.execcmd('ps aux|grep %s | grep -v sh | grep -v grep | grep -v python | grep %d' % (self.m_procName, pid))
            #打印一下
            print("getSubProcCpu lineList:", lineList)

            #是否能查询到ps字符串
            if len(lineList) > 0:
                fCpu = dataconvert.str2float(lineList[0][2])
                result = True
        except:
            print("getSubProcCpu except")
        print("\r\n getSubProcCpu: get sub subproc end, result:", result, ", fCpu:", fCpu)
        return (result, fCpu)

    #获取子进程PID
    '''
    # ps lax | grep reclive | grep -v grep
    0     0 25960     1  18   0  11164  2252 wait   S    ?          0:00 ./vcs_reclive
    1     0 25961 25960  23   0 519912 69252 wait   Sl   ?         81:04 ./vcs_reclive
    '''
    def getSubProcessPID(self):
        ps_string = ""
        #分析开始
        subid = 0
        try:
            lineList = []
            #例子
            #"0     0 25960     1  18   0  11164  2252 wait   S    ?          0:00 ./vcs_reclive \n1     0 25961 25960  23   0 519912 69252 wait   Sl   ?         81:04 ./vcs_reclive"
            cmd = 'ps lax | grep %s | grep -v python | grep -v grep' % (self.m_procName)
            print("getSubProcessPID execcmd.execcmd:" , cmd)
            lineList = execcmd.execcmd(cmd)
            #打印一下
            print("getSubProcessPID return:" , lineList)

            #分析每一行
            for line in lineList:
                if line[3] != "1":
                    subid = dataconvert.str2int(line[2])

            '''
            [root@sss ~]# ps lax | grep vcs_test | grep -v grep
            0     0   957   927  18   0   2772   732 wait   S+   pts/8      0:00 ./vcs_test
            1     0   958   957  25   0   2772   112 -      R+   pts/8     18:50 ./vcs_test
            '''
            #另外一种分析法
            if subid == 0:
                if lineList[0][2] == lineList[1][3]:
                    subid = lineList[1][2]
                if lineList[1][2] == lineList[0][3]:
                    subid = lineList[0][2]
        except:
            print("getSubProcessPID except")
        return subid

#-------------------------------------------------------------------------------
def main():
    proc = CProcCpuMonitor("vcs_live", 80, 0, 3)
    proc.getSubProcessPID()
    while True:
        time.sleep(1)
        (isError, fCpu)= proc.checkIsError()
        if isError == True:
            print("*********TEST OK, CHECK ERROR, cpu:", fCpu)

if __name__ == '__main__':
    main()



















